import router from '@/router'
import { getToken } from './utils/auth'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
import { asyncRoutes } from '@/router/asyncRoutes'
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = getToken()
  const whitelist = ['/login', '/404']
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
      if (!store.state.user.userInfo.userId) { // 调用action函数 这个位置哦 !!!!!
        const res = await store.dispatch('user/fetchUserInfo')
        const menus = res.roles.menus
        console.log(menus, asyncRoutes)
        // const filters = asyncRoutes.filter(route => menus.includes(route.children[0]))
        const filterRoutes = asyncRoutes.filter(route => menus.includes(route.children[0].name))

        console.log(filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }
        ])
        store.commit('menu/setMenuList', filterRoutes)
      }
    }
  } else {
    if (whitelist.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done()
})
